import { http } from "@/utils/http";
import type { ApiResponse } from "../user";
import { ensureArray, normalisePagination, toNumber } from "@/api/_helpers";

const CONFIG_BASE = "/system/config";

export interface ConfigFilterParams {
  page?: number;
  page_size?: number;
  keyword?: string;
  category?: string;
  status?: string | number;
}

export interface ConfigItem {
  id: number;
  config_key: string;
  value_type: string;
  config_value: unknown;
  description?: string;
  category?: string;
  status: number;
  create_time?: string;
  update_time?: string;
  [key: string]: any;
}

export interface ConfigListResult {
  list: Array<ConfigItem>;
  categories: Array<string>;
  pagination: {
    total: number;
    pageSize: number;
    currentPage: number;
  };
  raw?: any;
}

export interface ConfigCreatePayload {
  config_key: string;
  value_type: ConfigItem["value_type"];
  config_value: unknown;
  category?: string;
  status?: number;
  description?: string;
}

export interface ConfigUpdatePayload {
  value_type?: ConfigItem["value_type"];
  config_value?: unknown;
  category?: string;
  status?: number;
  description?: string;
}

const mapConfig = (item: Record<string, any>): ConfigItem => ({
  id: toNumber(item.id, 0),
  config_key: item.config_key ?? item.key ?? "",
  value_type: item.value_type ?? item.type ?? "string",
  config_value: item.config_value ?? item.value,
  description: item.description ?? "",
  category: item.category ?? "",
  status: toNumber(item.status ?? 1, 1),
  create_time: item.create_time ?? item.created_at ?? "",
  update_time: item.update_time ?? item.updated_at ?? ""
});

const fetchList = async (
  params: ConfigFilterParams = {}
): Promise<ConfigListResult> => {
  const page = toNumber(params.page, 1);
  const pageSize = toNumber(params.page_size, 10);
  const res = await http.request<ApiResponse<any>>("get", CONFIG_BASE, {
    params: {
      ...params,
      page,
      page_size: pageSize
    }
  });

  const payload = (res?.data as Record<string, any>) ?? {};
  const listContainer =
    payload.list ?? payload.data ?? payload.records ?? payload.items ?? {};
  const listSource = Array.isArray(listContainer?.data)
    ? listContainer.data
    : Array.isArray(listContainer)
      ? listContainer
      : [];
  const list = ensureArray<Record<string, any>>(listSource).map(mapConfig);
  const pagination = normalisePagination(
    payload.pagination ?? listContainer ?? payload,
    page,
    pageSize,
    Array.isArray(listSource) ? listSource.length : list.length
  );
  const categories = ensureArray<string>(payload.categories ?? []);

  return {
    list,
    categories,
    pagination: {
      total: pagination.total,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    },
    raw: payload
  };
};

const create = async (payload: ConfigCreatePayload) => {
  return http.request<ApiResponse<any>>("post", CONFIG_BASE, {
    data: payload
  });
};

const update = async (id: number, payload: ConfigUpdatePayload) => {
  return http.request<ApiResponse<any>>("put", `${CONFIG_BASE}/${id}`, {
    data: payload
  });
};

const remove = async (id: number) => {
  return http.request<ApiResponse<any>>("delete", `${CONFIG_BASE}/${id}`);
};

export default {
  fetchList,
  create,
  update,
  remove
};
